package com.edroid.apkhooker.home;

import java.io.File;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;


/**
 * This class holds the per-item data in our Loader.
 */
public class AppEntry {
	
	public AppEntry(ApplicationInfo info) {
		this(null, info);
	}
	
	public AppEntry(Context context, ApplicationInfo info) {
		mContext = context.getApplicationContext();
		mInfo = info;
		mApkFile = new File(info.sourceDir);
	}

	public ApplicationInfo getApplicationInfo() {
		return mInfo;
	}

	public String getLabel() {
		return mLabel;
	}
	
	public String getPackgeName() {
		return mInfo.packageName;
	}
	
	public long getLastUpdateTime() {
		if(lastUpdateTime == -1) {
			PackageManager pm = mContext.getPackageManager();
			try {
				lastUpdateTime = pm.getPackageInfo(mInfo.packageName, 0).lastUpdateTime;
			} catch (NameNotFoundException e) {
				lastUpdateTime = 0;
			}
		}
		
		return lastUpdateTime;
	}

	public Drawable getIcon() {
		PackageManager pm = mContext.getPackageManager();
		
		if (mIcon == null) {
			if (mApkFile.exists()) {
				mIcon = mInfo.loadIcon(pm);
				return mIcon;
			} else {
				mMounted = false;
			}
		} else if (!mMounted) {
			// If the app wasn't mounted but is now mounted, reload
			// its icon.
			if (mApkFile.exists()) {
				mMounted = true;
				mIcon = mInfo.loadIcon(pm);
				return mIcon;
			}
		} else {
			return mIcon;
		}

		return mContext.getResources().getDrawable(android.R.drawable.sym_def_app_icon);
	}

	@Override
	public String toString() {
		return mLabel;
	}

	void loadLabel(Context context) {
		if (mLabel == null || !mMounted) {
			if (!mApkFile.exists()) {
				mMounted = false;
				mLabel = mInfo.packageName;
			} else {
				mMounted = true;
				CharSequence label = mInfo.loadLabel(context.getPackageManager());
				mLabel = label != null ? label.toString() : mInfo.packageName;
			}
		}
	}

	long lastUpdateTime = -1;
	final Context mContext;
	public final ApplicationInfo mInfo;
	public final File mApkFile;
	public String mLabel;
	public Drawable mIcon;
	public boolean mMounted;
	public boolean mChecked;
}
